package com.kakarote.hrm.service.impl;

import com.google.common.collect.Lists;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.hrm.entity.PO.HrmEmployeeContacts;
import com.kakarote.hrm.entity.PO.HrmEmployeeContactsData;
import com.kakarote.hrm.mapper.HrmEmployeeContactsMapper;
import com.kakarote.hrm.service.IHrmEmployeeContactsDataService;
import com.kakarote.hrm.service.IHrmEmployeeContactsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工联系人 服务实现类
 * </p>
 *
 * @author huangmingbo
 * @since 2020-05-12
 */
@Service
public class HrmEmployeeContactsServiceImpl extends BaseServiceImpl<HrmEmployeeContactsMapper, HrmEmployeeContacts> implements IHrmEmployeeContactsService {


    @Autowired
    private HrmEmployeeContactsMapper employeeContactsMapper;
    @Autowired
    private IHrmEmployeeContactsDataService contactsDataService;

    @Override
    public Integer verifyUnique(String fieldName, String value, Long contactsId) {
        return getBaseMapper().verifyUnique(fieldName, value, contactsId);
    }

    @Override
    public List<Map<String, Object>> queryEmployeeContactsListMap(List<Long> employeeIds) {
        List<Map<String, Object>> contactList = employeeContactsMapper.queryEmployeeContactsListMap(employeeIds);
        if (contactList != null && !contactList.isEmpty()) {
            // 自定义联系人字段
            List<HrmEmployeeContactsData> contactsFieldValueList = contactsDataService.queryEmployeeContactsDataList(new ArrayList<>(), Lists.newArrayList(1178L, 1179L));
            Map<Long, List<HrmEmployeeContactsData>> contactsFieldValueGroup = new HashMap<>();
            if (contactsFieldValueList != null && !contactsFieldValueList.isEmpty()) {
                contactsFieldValueGroup = contactsFieldValueList.stream().collect(Collectors.groupingBy(HrmEmployeeContactsData::getContactsId));
            }

            for (Map<String, Object> map : contactList) {
                List<HrmEmployeeContactsData> dataList = contactsFieldValueGroup.get(Long.valueOf(map.get("contactsId").toString()));
                if (dataList != null && !dataList.isEmpty()){
                    for (HrmEmployeeContactsData data : dataList) {
                        // 民族
                        if (data.getFieldId() == 1178L){
                            map.put("contactsNation", data.getFieldValue());
                        }
                        // 政治面貌
                        if (data.getFieldId() == 1179L) {
                            map.put("politicalOutlook", data.getFieldValue());
                        }
                    }
                }

            }
        }
        return contactList;
    }
}
